﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.BLL.Ali;
using CRM.MODEL;
using CRM.UTIL;
using CRM.WEB.CommonClass;

namespace CRM.WEB.Parts
{
    public partial class ImportParts : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpLoad_Click(object sender, EventArgs e)
        {
            if (fileControl.HasFile)
            {
                string folder = string.Empty;
                string dirPath = CommonClass.Common.GetUpLoadDirPath(Server, out folder);


                string fileName = fileControl.FileName;
                string strFileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1);

                fileName = CommonClass.Common.GetNewFileName(dirPath, fileName);
                if (!string.IsNullOrEmpty(strFileExt) && (strFileExt.ToLower() == "xls") ||
                    strFileExt.ToLower() == "xlsx")
                {
                    //upload to server
                    string serverName = Server.MapPath(folder).Trim('\\') + "\\" + fileName;
                    fileControl.PostedFile.SaveAs(serverName);

                    try
                    {
                        var dt = ExcelHelper.ExcelToTable(serverName);
                        var obj = new BLL.PartsB();
                        var objCategory = new BLL.PartsCategoryB();
                        var objModel = new BLL.PartsModelsB();
                        var objSupplier = new BLL.PartsSuppliersB();
                        var objPartsModelMapping = new BLL.PartsModelMappingB();
                        var sb = new StringBuilder();
                        var session = SessionBox.GetUserSession();
                        int succCount = 0;
                        int updateCount = 0;
                        if (dt.Columns.Contains("供应商料号") &&
                            dt.Columns.Contains("所属分类") &&
                            dt.Columns.Contains("供应商") &&
                            dt.Columns.Contains("供应商料号") &&
                            dt.Columns.Contains("配件名称") &&
                            dt.Columns.Contains("配件显示名称") &&
                            dt.Columns.Contains("材料及规格") &&
                            dt.Columns.Contains("采购价格") &&
                            dt.Columns.Contains("销售价格") &&
                            dt.Columns.Contains("交期") &&
                            dt.Columns.Contains("账期") &&
                            dt.Columns.Contains("库存") &&
                            dt.Columns.Contains("最小出售数量") &&
                            dt.Columns.Contains("适用机型"))
                        {
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                for (var i = 0; i < dt.Rows.Count; i++)
                                {
                                    #region 循环处理

                                    try
                                    {
                                        var dr = dt.Rows[i];
                                        var supplierNo = dr["供应商料号"].ToString();
                                        var categoryCaode = dr["所属分类"].ToString();
                                        var supplierName = dr["供应商"].ToString();
                                        var supplierNO = dr["供应商料号"].ToString();
                                        var partsName = dr["配件名称"].ToString();
                                        var partsDisplayName = dr["配件显示名称"].ToString();
                                        var materialSpecification = dr["材料及规格"].ToString();
                                        var procurementPrice = dr["采购价格"].ToString();
                                        var marketPrice = dr["销售价格"].ToString();
                                        var getGoodsDays = dr["交期"].ToString();
                                        var payGoodsDays = dr["账期"].ToString();
                                        var stockQuantity = dr["库存"].ToString();
                                        var leastSellCount = dr["最小出售数量"].ToString();
                                        var modelName = dr["适用机型"].ToString();

                                        if(string.IsNullOrEmpty(supplierNo)||string.IsNullOrEmpty(categoryCaode)||string.IsNullOrEmpty(supplierName)||string.IsNullOrEmpty(supplierNO)||string.IsNullOrEmpty(partsName)||string.IsNullOrEmpty(partsDisplayName))
                                            continue;
                                        //2.获取所属分类、所属供应商
                                        var cateStu = new GetPartsCategory {CATEGORYCODEVALUE = categoryCaode};
                                        var categoryDt =
                                            objCategory.GetPartsCategory(ref cateStu);
                                        if (categoryDt != null && categoryDt.Rows.Count > 0)
                                        {
                                            var supplierStu = new MODEL.GetPartsSuppliers
                                            {
                                                SUPPLIERNAMEVALUE = supplierName
                                            };
                                            var supplierDt = objSupplier.GetPartsSuppliers(ref supplierStu);
                                            if (supplierDt != null && supplierDt.Rows.Count > 0)
                                            {
                                                decimal pPrice;
                                                decimal.TryParse(procurementPrice, out pPrice);
                                                decimal mPrice;
                                                decimal.TryParse(marketPrice, out mPrice);
                                                int gDays;
                                                int.TryParse(getGoodsDays, out gDays);
                                                int pDays;
                                                int.TryParse(payGoodsDays, out pDays);
                                                int stockQu;
                                                int.TryParse(stockQuantity, out stockQu);
                                                int leastSellC;
                                                int.TryParse(leastSellCount, out leastSellC);

                                                //1.判断供应商料号是否存在， 存在则不添加
                                                var getStu = new MODEL.GetParts {SUPPLIERPARTSNOVALUE = supplierNo};
                                                var existDt = obj.GetParts(ref getStu);
                                                if (existDt != null && existDt.Rows.Count > 0)
                                                {
                                                    //sb.AppendFormat("第{0}行数据已存在，供应商料号{1}\r\n", i + 1, supplierNo);
                                                    int maxID;
                                                    var arr = existDt.Rows[0]["WisetechPartsNO"].ToString().Split('-');
                                                    var partsId = existDt.Rows[0]["ID"].ToString();
                                                    var updateStu = new EditParts
                                                    {
                                                        #region Init
                                                        ACTION_VALUE ="Update",
                                                        ID_VALUE = partsId,
                                                        CATEGORYID_VALUE =
                                                            int.Parse(categoryDt.Rows[0]["ID"].ToString()),
                                                        PARTSSUPPLIERID_VALUE =
                                                            int.Parse(supplierDt.Rows[0]["ID"].ToString()),
                                                        WISETECHPARTSNO_VALUE =
                                                            categoryDt.Rows[0]["CategoryCode"] + "-" +
                                                            (arr.Length>1?arr[1]:obj.GetRandomNO(out maxID)) + "-" +
                                                            supplierDt.Rows[0]["SupplierCode"],
                                                        SUPPLIERPARTSNO_VALUE = supplierNO,
                                                        PARTSNAME_VALUE = partsName,
                                                        PARTSDISPLAYNAME_VALUE =
                                                            string.IsNullOrEmpty(partsDisplayName)
                                                                ? partsName
                                                                : partsDisplayName,
                                                        MATERIALSPECIFICATION_VALUE = materialSpecification,
                                                        PROCUREMENTPRICE_VALUE = pPrice,
                                                        //PROCUREMENTCURRENCY_VALUE = "CNY",
                                                        MARKETPRICE_VALUE = mPrice,
                                                        //MARKETCURRENCY_VALUE = "CNY",
                                                        GETGOODSDAYS_VALUE = gDays,
                                                        PAYGOODSDAYS_VALUE = pDays,
                                                        STOCKQUANTITY_VALUE = stockQu,
                                                        LEASTSELLCOUNT_VALUE = leastSellC,
                                                        //REMARK_VALUE = string.Empty,
                                                        //ISAVAILABLE_VALUE = true,
                                                        //CREATEBY_VALUE = session.LoginName,
                                                        //CREATETIME_VALUE = DateTime.Now,
                                                        LASTMODIFYBY_VALUE = session.LoginName,
                                                        LASTMODIFYTIME_VALUE = DateTime.Now
                                                        #endregion
                                                    };
                                                    obj.EditParts(ref updateStu);
                                                    updateCount++;

                                                    var getModelStu = new GetPartsModels
                                                    {
                                                        MODELDISPLAYNAMEVALUE = modelName
                                                    };
                                                    var modelDt = objModel.GetPartsModels(ref getModelStu);
                                                    if (modelDt != null && modelDt.Rows.Count > 0)
                                                    {
                                                        var modelID = modelDt.Rows[0]["ID"].ToString();
                                                        var getMapp = new GetPartsModelMapping
                                                        {
                                                            PARTSIDVALUE = partsId,
                                                            MODELIDVALUE = modelID
                                                        };
                                                        var mappDt =
                                                            objPartsModelMapping.GetPartsModelMapping(ref getMapp);
                                                        if (mappDt == null || mappDt.Rows.Count <= 0)
                                                        {
                                                            var mappStu = new EditPartsModelMapping
                                                            {
                                                                ACTION_VALUE = "Insert",
                                                                MODELID_VALUE = modelDt.Rows[0]["ID"].ToString(),
                                                                PARTSID_VALUE = existDt.Rows[0]["ID"].ToString()
                                                            };
                                                            objPartsModelMapping.EditPartsModelMapping(ref mappStu);
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    int maxID;
                                                    var partsStu = new EditParts
                                                    {
                                                        #region Init
                                                        ACTION_VALUE = "Insert",
                                                        GUID_VALUE = Guid.NewGuid().ToString("N"),
                                                        CATEGORYID_VALUE =
                                                            int.Parse(categoryDt.Rows[0]["ID"].ToString()),
                                                        PARTSSUPPLIERID_VALUE =
                                                            int.Parse(supplierDt.Rows[0]["ID"].ToString()),
                                                        WISETECHPARTSNO_VALUE =
                                                            categoryDt.Rows[0]["CategoryCode"] + "-" +
                                                            obj.GetRandomNO(out maxID) + "-" +
                                                            supplierDt.Rows[0]["SupplierCode"],
                                                        SUPPLIERPARTSNO_VALUE = supplierNO,
                                                        PARTSNAME_VALUE = partsName,
                                                        PARTSDISPLAYNAME_VALUE =
                                                            string.IsNullOrEmpty(partsDisplayName)
                                                                ? partsName
                                                                : partsDisplayName,
                                                        MATERIALSPECIFICATION_VALUE = materialSpecification,
                                                        PROCUREMENTPRICE_VALUE = pPrice,
                                                        PROCUREMENTCURRENCY_VALUE = "CNY",
                                                        MARKETPRICE_VALUE = mPrice,
                                                        MARKETCURRENCY_VALUE = "CNY",
                                                        GETGOODSDAYS_VALUE = gDays,
                                                        PAYGOODSDAYS_VALUE = pDays,
                                                        STOCKQUANTITY_VALUE = stockQu,
                                                        LEASTSELLCOUNT_VALUE = leastSellC,
                                                        REMARK_VALUE = string.Empty,
                                                        ISAVAILABLE_VALUE = true,
                                                        CREATEBY_VALUE = session.LoginName,
                                                        CREATETIME_VALUE = DateTime.Now,
                                                        LASTMODIFYBY_VALUE = session.LoginName,
                                                        LASTMODIFYTIME_VALUE = DateTime.Now
                                                        #endregion
                                                    };
                                                    int res = obj.EditParts(ref partsStu);
                                                    if (res > 0)
                                                    {
                                                        succCount++;
                                                        int mID;
                                                        obj.GetRandomNO(out mID);
                                                        var getModelStu = new GetPartsModels
                                                        {
                                                            MODELDISPLAYNAMEVALUE = modelName
                                                        };
                                                        var modelDt = objModel.GetPartsModels(ref getModelStu);
                                                        if (modelDt != null && modelDt.Rows.Count > 0)
                                                        {
                                                            var mappStu = new EditPartsModelMapping
                                                            {
                                                                ACTION_VALUE = "Insert",
                                                                MODELID_VALUE = modelDt.Rows[0]["ID"].ToString(),
                                                                PARTSID_VALUE = mID
                                                            };
                                                            objPartsModelMapping.EditPartsModelMapping(ref mappStu);
                                                        }
                                                    }

                                                }
                                            }
                                            else
                                            {
                                                sb.AppendFormat("第{0}行所属供应商不存在，所属供应商：{1}\r\n", i + 1, supplierName);
                                            }
                                        }
                                        else
                                        {
                                            sb.AppendFormat("第{0}行所属分类不存在，所属分类：{1}\r\n", i + 1, categoryCaode);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        sb.AppendFormat("第{0}行异常：{1}\r\n", i + 1, ex.Message);
                                    }

                                    #endregion
                                }

                            }
                            else
                            {
                                ShowAlert("导入表中无数据.");
                            }
                        }
                        else
                        {
                            ShowAlert("导入文件不合法，必须包含列：供应商料号、所属分类、供应商、配件名称、配件显示名称、材料及规格、采购价格、销售价格、交期、账期、库存、最小出售数量、适用机型");
                        }

                        //ShowAlert();
                        txtInfo.Text = "新增数量：" + succCount + "\r\n更新数量：" + updateCount + "\r\n" + sb.ToString();
                    }
                    catch (Exception ex)
                    {
                        ShowAlert(ex.Message);
                    }
                }
                else
                {
                    ShowAlert("请选择正确的文件类型！");
                }
            }
            else
            {
                ShowAlert("请选择文件！");
            }
        }
    }
}